package com.baizan.daka.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.alipay.sdk.sys.Module
import com.baizan.base.BaseActivity
import com.baizan.daka.MyApp
import com.baizan.daka.event.HomeEvent
import com.baizan.daka.event.PayEvent
import com.baizan.daka.mvp.model.bean.VipBean
import com.baizan.daka.mvp.model.bean.PackageBean
import com.baizan.daka.mvp.model.bean.PayChannelBean
import com.baizan.daka.pay.AuthResult
import com.baizan.daka.pay.PayResult
import com.baizan.daka.showToast
import com.baizan.daka.ui.adapter.PackageAdapter
import com.baizan.daka.ui.adapter.PayChannelAdapter
import com.baizan.daka.ui.adapter.VipHomeAdapter
import com.baizan.daka.ui.contract.PayContract
import com.baizan.daka.ui.presenter.PayPresenter
import com.baizan.daka.util.HyperTextUtil
import com.dianzan.daka.R
import kotlinx.android.synthetic.main.act_pay.*
import org.greenrobot.eventbus.EventBus


class PayActivity : BaseActivity<PayPresenter>(), PayContract.View {
    var packageBean: PackageBean? = null
    var vipBean: VipBean? = null
    private val payChannelAdapter :PayChannelAdapter =PayChannelAdapter()
    companion object {
        fun startPayPackage(context: Context, packageBean: PackageBean) {
            val intent = Intent(context, PayActivity::class.java)
            intent.putExtra("vipInfo", packageBean)
            context.startActivity(intent)
        }

        fun startPayVip(context: Context, vipBean: VipBean) {
            val intent = Intent(context, PayActivity::class.java)
            intent.putExtra("vip", vipBean)
            context.startActivity(intent)
        }
    }

    override fun initPresenter(): PayPresenter = PayPresenter(this)

    override fun layoutId(): Int = R.layout.act_pay

    override fun initData() {
        var temp = intent.getSerializableExtra("vipInfo")
        var vipTemp = intent.getSerializableExtra("vip")
        temp?.let {
            it as PackageBean
            packageBean = it
        }
        vipTemp?.let {
            it as VipBean
            vipBean = it
        }
        var mLinearLayoutManager = LinearLayoutManager(this)
        mLinearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        pay_cl.layoutManager = mLinearLayoutManager
        packageBean?.let {
            val adapter = PackageAdapter(1)
            pay_cl.adapter = adapter
            adapter.setNewData(listOf(it))
            pay_value.text = HyperTextUtil.build("合计：")
                .appendColor("￥${it.packagePrice}", Color.parseColor("#FE0000")).Builder()
        }
        vipBean?.let {
            val adapter = VipHomeAdapter(1)
            pay_cl.adapter = adapter
            adapter.setNewData(listOf(it))
            pay_value.text = HyperTextUtil.build("合计：")
                .appendColor("￥${it.unitAmount}", Color.parseColor("#FE0000")).Builder()
        }
        ok.setOnClickListener {
          val payChannel =  payChannelAdapter.getIndexBean()
            packageBean?.let {
                presenter?.payHtml(it.id, 2,payChannel.channelCode)

            }
            vipBean?.let {
                presenter?.payHtml(it.id.toLong(), 1,payChannel.channelCode)
            }
        }
        var payChannelLM = LinearLayoutManager(this)
        payChannelLM.orientation = LinearLayoutManager.VERTICAL
        pay_channel.layoutManager = payChannelLM
        pay_channel.adapter = payChannelAdapter
    }

    override fun initView() {

    }

    override fun start() {
        presenter?.getPayChannelList()
    }

    override fun paySuccess(order: String) {

        Module.packageName = "com.xunmeng.pinduoduo"
        val payRunnable = Runnable {
            val alipay = PayTask(this)
            val result =
                alipay.payV2(order, true)
            Log.i("msp", result.toString())
            val msg = Message.obtain()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        // 必须异步调用

        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    override fun payHtmlSuccess(order: String) {
        WebActivity.start(this, order)
    }

    override fun getPayChannelListSuccess(data: List<PayChannelBean>) {
        payChannelAdapter.setNewData(data)
    }

    private val SDK_PAY_FLAG = 1
    private val SDK_AUTH_FLAG = 2

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult =
                        PayResult(msg.obj as Map<String?, String?>)

                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo: String = payResult.getResult() // 同步返回需要验证的信息
                    val resultStatus: String = payResult.getResultStatus()
                    // 判断resultStatus 为9000则代表支付成功
                    Log.e("payResult", payResult.toString())
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showToast("支持成功")
                        EventBus.getDefault().post(PayEvent())
                        EventBus.getDefault().post(HomeEvent(0))
                        MyApp.finishAct(FlowPackageActivity::class.java)
                        finish()
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast("支付失败")
                    }
                }
                SDK_AUTH_FLAG -> {
                    val authResult = AuthResult(
                        msg.obj as Map<String?, String?>,
                        true
                    )
                    val resultStatus = authResult.resultStatus

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(
                            resultStatus,
                            "9000"
                        ) && TextUtils.equals(authResult.resultCode, "200")
                    ) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        showToast("认证授权成功")
                    } else {
                        // 其他状态值则为授权失败
                        showToast("认证授权失败")
                    }
                }
                else -> {
                }
            }
        }
    }
}